var getTableId = function (tagName) {
    var tableJSONs = JSON.parse(igrx.getSql("select table_id, tag_name from log_toc", {
        dbgroup: "mssql",
        offset: 0,
        limit: -1,
        skip: 0,
        outfmt: "json"
    }));
    for (var i = 0; i < tableJSONs.length; i++) {
        if (tableJSONs[i].tag_name == tagName) {
            strRtn = tableJSONs[i].table_id;
        }
    }
    return strRtn;
}
var getDateAxis = function () {
    let rtnArray = [];
    var dateObj = new Date(new Date().getTime() - 60 * 60 * 1000);
    for (var i = 0; i < 7; i++) {
        var hour = dateObj.getHours();
        var minutes = dateObj.getMinutes();
        if (minutes < 10) {
            minutes = '0' + minutes;
        }
        rtnArray.push(hour + ':' + minutes);
        dateObj = new Date(dateObj.getTime() + 60 / 7 * 60 * 1000);
    }
    return rtnArray;
}

var qryTagValue = function (tagName) {
    let rtnArray = [];
    var dateObj = new Date(new Date().getTime() - 144 * 60 * 60 * 1000);
    for (var i = 0; i < 6; i++) {
        var tableId = getTableId(tagName);
        var value = JSON.parse(igrx.getSql("select nvalue from log_" + tableId + " where DATEDIFF(d, time_stamp, CAST('" + dateObj + "' as datetime)) = 0", {
            dbgroup: "mssql",
            offset: 0,
            limit: -1,
            skip: 0,
            outfmt: "json"
        }));
        if (value.length !== 1) {
            rtnArray.push(0);
        } else {
            rtnArray.push(JSON.parse(value)[0].nvalue);
        }
    }
    rtnArray.push(igrx.getTag(tagName + "_CURRENT"));
    return rtnArray;
}

var qryNegTagValue = (sourceArray) => {
    return sourceArray.map((x) => {
        return -x;
    });
}